/**
 * Created by 功振 on 2016/1/30.
 */
angular.module('NatureCloud').controller('BuildHistoryController', ["$scope", "$state", "$stateParams", "$cookies", "buildQuery", "buildStop", function ($scope, $state, $stateParams, $cookies, buildQuery, buildStop) {
    //var username = "kidqhj";
    /*function dump_obj(myObject) {
     var s = "";
     for (var property in myObject) {
     s = s + "\n " + property + ": " + myObject[property];
     }
     return s;
     }*/
    var user = $cookies.get("username");
    // var build =  $stateParams.buildInfo;
    // delete(build['params']);
    // build.isCI = false;
    // build.username = '';
    // build.password = '';
    // build.user = user;
    // console.log(build);

    //console.log("stateParams:" + dump_obj($stateParams));
    var runID = $stateParams.runID;
    $scope.jobName = runID;
    buildQuery(user, runID).then(function (r) {
        // alert success
        $scope.buildInfo = r.data.meta;
        $scope.runInfos = [];
        // build.buildHistory = r.data.builds.length;
        for (var i = 0; i < r.data.builds.length; i++) {
            var runInfo = r.data.builds[i];
            // console.log(i + ":" + runInfo.result);
            var startDate = new Date(runInfo.timestamp);
            runInfo.startDate = startDate.toLocaleDateString() + " " + startDate.toLocaleTimeString();
            runInfo.durationSeconds = Math.round(runInfo.duration/1000);
            switch (runInfo.result) {
                case "SUCCESS":
                    runInfo.statusColor = "cbp_tmicon timeline-bg-success";
                    runInfo.statusSignal = "fa-check";
                    runInfo.statusTitle = "成功";
                    break;
                case "FAILURE":
                case "ABORTED":
                    runInfo.statusColor = "cbp_tmicon timeline-bg-red";
                    runInfo.statusSignal = "fa-times";
                    runInfo.statusTitle = "失败";
                    break;
                default:
                    runInfo.statusColor = "cbp_tmicon timeline-bg-info";
                    runInfo.statusSignal = "fa-play";
                    runInfo.statusTitle = "运行中";
                    runInfo.isRunning = true;
            }
            if(runInfo.auto_manual === 'auto'){
                runInfo.auto_manual = '自动构建';
            }else if(runInfo.auto_manual === 'manual'){
                runInfo.auto_manual = '手动构建';
            }else if(runInfo.auto_manual === 'test'){
                runInfo.auto_manual = '测试Dockerfile';
            }else if(runInfo.auto_manual === 'update'){
                runInfo.auto_manual = '更新Dockerfile';
            }else{
                runInfo.auto_manual = '手动构建';
            }
            //runInfo.disabled = true;
            // runInfo.branch_type = ucfirst(runInfo.branch_type);
            $scope.runInfos[i] = runInfo;
        }
        // console.log(r.data + "buildList query succeeded");

        // function ucfirst(str) {
        //     var str = str.toLowerCase();
        //     str = str.replace(/\b\w+\b/g, function(word){
        //         return word.substring(0,1).toUpperCase()+word.substring(1);
        //     });
        //     return str;
        // }

        $scope.getBuildDetail = function (runID, buildSeq, buildInfo, runInfo) {
            var buildInfo = $scope.runInfos[$scope.runInfos.length - buildSeq];
            if(buildInfo.statusTitle === "运行中"){
                $state.go("cp.buildrunningdetail", {
                    jobName: runID,
                    buildSeq: buildSeq,
                    buildInfo: buildInfo,
                    runInfo: runInfo
                });
            }else{

                $state.go("cp.builddetail", {
                    jobName: runID,
                    buildSeq: buildSeq,
                    buildInfo: buildInfo,
                    runInfo: runInfo
                });
            }

        };
    }, function (r) {
        // alert fail
        alertify.error(r.data + "build query failed")
        // console.log(r.data + "build query failed");
    });

    $scope.currentPageRunInfos = [];
    $scope.currentPage = 1;
    $scope.numPerPage = 10;
    $scope.$watch("runInfos + currentPage", function() {
        if ($scope.runInfos) {
            var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;
            $scope.currentPageRunInfos = $scope.runInfos.slice(begin, end);
        }
    });

    $scope.stop = function (jobID, runID,e) {
      e.stopPropagation();

      var user = $cookies.get("username");
        buildStop(user, jobID, runID).then(function (r) {
            var data = r.data.data;
            var _ret = r.data.ret;
            if (_ret === true){
                $scope.$watchCollection('currentPageRunInfos', function () {
                    for (var i = 0; i < $scope.currentPageRunInfos.length; i++) {
                        if ($scope.currentPageRunInfos[i].id === data.id){
                            var startDate = new Date(data.timestamp);
                            $scope.currentPageRunInfos[i].startDate = startDate.toLocaleDateString() + " " + startDate.toLocaleTimeString();
                            $scope.currentPageRunInfos[i].result = data.result;
                            $scope.currentPageRunInfos[i].statusColor = "cbp_tmicon timeline-bg-red";
                            $scope.currentPageRunInfos[i].statusSignal = "fa-times";
                            $scope.currentPageRunInfos[i].statusTitle = "失败";
                            $scope.currentPageRunInfos[i].isRunning = false;
                            $scope.currentPageRunInfos[i].durationSeconds = Math.round(data.duration/1000);
                            $scope.currentPageRunInfos[i].timestamp = data.timestamp;
                        }
                    }
                });
                alertify.success("build stop succeeded");
            }else {
                alertify.error("build stop failed");
            }

        }, function (r) {
            // alert fail
            alertify.error(r + "build stop failed");
            // console.log(r + "build stop failed");
        });
    };

    $scope.getBuildDetail = function (runID, buildSeq, buildInfo, runInfo) {

        var buildInfo = $scope.runInfos[$scope.runInfos.length - buildSeq];
        if(buildInfo.statusTitle === "运行中"){
            $state.go("cp.buildrunningdetail", {
                jobName: runID,
                buildSeq: buildSeq,
                buildInfo: buildInfo,
                runInfo: runInfo
            });
        }else{

            $state.go("cp.builddetail", {
                jobName: runID,
                buildSeq: buildSeq,
                buildInfo: buildInfo,
                runInfo: runInfo
            });
        }

    };

}]);
